<?php

namespace App\Kuafu\Export\Controller\Merchant;

use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Export\Model\ExportDownloadModel;
use App\Kuafu\Export\Service\ExportDownloadService;
use App\Kuafu\Order\Enum\OrderMerchantEnum;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use function auth;

class ExportDownloadsController extends BaseController
{
    public function lists(Request $request): JsonResponse
    {
        $pageSize = $request->get('pageSize', 20);
        $pageNum  = $request->get('pageNum', 1);

        $userId = auth('api')->user()->id ?? 0;

        $client = ExportDownloadModel::CLIENT_TYPE_APP;
        return $this->success(ExportDownloadService::lists($client, $userId, $pageSize, $pageNum));
    }

    public function delete(Request $request, int $id): JsonResponse
    {
        (new ExportDownloadModel())->del($id);

        return $this->success();
    }

    public function export(Request $request): JsonResponse
    {
        $shopId      = (int)$request->header('shopId');
        $showTimeTab = (int)$request->get('showTimeTab', 0);
        $showStartAt = (int)$request->get('showStartAt', 0);
        $showEndAt   = (int)$request->get('showEndAt', 0);
        $fileType    = (int)$request->get('fileType', 0);

        $request->merge(['shopId' => $shopId]);
        $this->validate($request, [
            'showTimeTab' => [
                'required',
                'integer',
                Rule::in(array_keys(OrderMerchantEnum::SHOW_TIME_TAB_TEXT)),
            ],
            'showStartAt' => 'nullable|integer|min:0',
            'showEndAt'   => 'nullable|integer|min:0',
        ]);

        $client = ExportDownloadModel::CLIENT_TYPE_APP;
        ExportDownloadService::export($client, $fileType, $shopId, $showTimeTab, $showStartAt, $showEndAt);

        return $this->success();
    }
}
